package com.treeliked.netdiskdemo.util;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Optional;

/**
 * cookie 工具类
 *
 * @author lqs2
 * @date 2018-12-12, Wed
 */
public class CookieUtils {


    /**
     * 获取请求中的指定的cookie的值
     *
     * @param request 请求
     * @param key     cookie key
     * @return value
     */
    public static String getCookieByName(HttpServletRequest request, String key) {
        if (request == null) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
        Optional<Cookie> first = Arrays.stream(cookies).filter(c -> StringUtils.equals(c.getName(), key)).findFirst();
        return first.map(Cookie::getValue).orElse(null);
    }


}
